package pers.corvey.studyjava.handler;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import pers.corvey.studyjava.exception.*;
import pers.corvey.studyjava.model.json.ServerMessageJson;

@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(value = NotFoundException.class)
    @ResponseStatus(code=HttpStatus.NOT_FOUND)
    public ServerMessageJson throwNotFoundExcepetion(Exception e) {
        return throwExceptionMsg(e);
    }
    
    @ExceptionHandler(value = {DAOException.class, InternalServerErrorException.class})
    @ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
    public ServerMessageJson throwDAOExcepetion(Exception e) {
        e.printStackTrace();
        return throwExceptionMsg(e);
    }
    
    @ExceptionHandler(value = BadRequestException.class)
    @ResponseStatus(code=HttpStatus.BAD_REQUEST)
    public ServerMessageJson throwBadRequestException(Exception e) {
        return throwExceptionMsg(e);
    }
    
    private ServerMessageJson throwExceptionMsg(Exception e) {
        ServerMessageJson messageJson = new ServerMessageJson();
        messageJson.setMessage(e.getMessage());
        return messageJson;
    }
    
}
